<?php

class Adept_Db_MySql_RecordSet implements Iterator 
{
    
    protected $key;
    protected $current;
    protected $valid = false;    
    protected $connection;
    protected $fetchMode;
    protected $queryId;
    protected $query;
    
    public function __construct($connection, $query, $fetchMode = null) 
    {
        $this->connection = $connection;
        $this->fetchMode = $fetchMode;
        $this->query = $query;
    }

    /**
     * @throws Adept_Db_Exception
     *
     */
    public function rewind() 
    {
        if (isset($this->queryId) && is_resource($this->queryId)) {
            if (mysql_data_seek($this->queryId, 0) === false) {
                throw new Adept_Db_Exception('Cannot rewind record set');    
            }
        } else {
            $query = $this->query;
            $this->queryId = $this->connection->execute($query);
        }
        $this->key = 0;
        $this->next();
    }
    
    public function valid() 
    {
        return $this->valid;
    }
     
    public function key() 
    {
        return $this->key;
    }
     
    public function current() 
    {
        return $this->current;
    }
     
    public function next() 
    {
        $this->current = mysql_fetch_array($this->queryId, $this->fetchMode);
        $this->valid = is_array($this->current);
        $this->key++;
    }
    
    public function getRowCount() 
    {
        if (is_null($this->queryId)) {
            $this->rewind();
        }
        return mysql_num_rows($this->queryId);
    }
    
    public function toArray()
    {
        $result = array();
        foreach ($this as $row) {
            $result[] = $row;
        }
        return $result;
    }
    
    public function getFirstRecord()
    {
        $this->rewind();
        return ($this->valid()) ? $this->current() : array();
    }
    
    public function getOneColumn()
    {
        $result = array();
        foreach ($this as $record) {
            $result[] = reset($record);
        }
        return $result;
    }
    
    public function getTwoColumns()
    {
        $result = array();
        foreach ($this as $record) {
            $result[reset($record)] = next($record);
        }
        return $result;        
    }
    
    public function getOneValue()
    {
        $this->rewind();
        return ($this->valid()) ? reset($this->current) : null;
    }
    
}
